﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetAppBlocks.Forms;
using DevExpress.XtraGrid.Columns;
using ProgNetComponents.Data;
using ProgNetDxComponents.Controls.Forms;
using ProgNetDxComponents.ExtenderProviders.Options;
using ProgNet.Constants;

namespace MiniKsiegowosc.Wrk.Ksiegi.VatZ
{
    public partial class FormWrkVatZ : ProgNetSpreadSheetForm
    {
        InputFormText _InputFormText;
        private InputFormText InputFormText
        {
            get
            {
                if (_InputFormText == null)
                {
                    _InputFormText = new InputFormText();
                    _InputFormText.ValidateValue += new EventHandler<ValidationEventArgs>(_InputFormText_ValidateValue);
                }
                return _InputFormText;
            }
        }

        void _InputFormText_ValidateValue(object sender, ValidationEventArgs e)
        {
            if (e.Value.AsString().Trim().IsNull())
            {
                e.Error = "Podaj nazwę";
            }
            else if (ProgNetDxComponents.ExtenderProviders.Browsers.BrowserCache.IsDisplayValueValid(ProgNet.Constants.BrowserNames.StpVatZ, e.Value))
            {
                e.Error = "Nazwa jest już zajęta";
            }
        }
        private bool LockEvents = false;
        List<DataRow> list = new List<DataRow>();

        public FormWrkVatZ()
        {
            InitializeComponent();
        }
        public FormWrkVatZ(int rok)
        {
            InitializeComponent();
            CurrentRecordId = rok;
        }
        protected override void FinishEdit()
        {
            base.FinishEdit();
            DataRow[] rows = wrkVatZDataSet.WRK_VATZ.Select();
            foreach (DataRow row in rows)
            {
                row.SetColumnValue("WRK_VATZ_ROK", row["WRK_VATZ_DATA_WYSTAWIENIA"].AsDateTime().Year);
            }
        }
        protected override ProgNetComponents.Data.ObjectKeyValuePair[] GetOpenParameters()
        {
            ObjectKeyValuePair k = new ObjectKeyValuePair("@ROK", CurrentRecordId);
            return new ObjectKeyValuePair[] { k };
        }
        protected override string FormText
        {
            get
            {
                return base.FormText + " Rok: " + CurrentRecordId.AsString();
            }
        }
        protected override bool ValidateRow(DataRow r, DevExpress.XtraGrid.Views.Grid.GridView gv)
        {
            bool result = base.ValidateRow(r, gv);
            if (gv == gvMain)
            {
                if (r["WRK_VATZ_DATA_WYSTAWIENIA"].IsNotNull())
                {
                    DateTime d = r["WRK_VATZ_DATA_WYSTAWIENIA"].AsDateTime();
                    if (d.Year != CurrentRecordId.AsInt())
                    {
                        list.Add(r);
                    }
                    if (!WrkTools.IsRokValid(d.Year))
                    {
                        r.SetColumnError("WRK_VATZ_DATA_WYSTAWIENIA", "Brak Roku Księgowego.");
                        AddError("Brak Roku Księgowego " + d.Year);
                        result = false;
                    }
                }
            }
            return result;
        }

        protected override void ValidateAll()
        {
            list.Clear();
            base.ValidateAll();

            if (list.Count > 0)
            {
                if (this.ShowDxYNQuestionDialog("Nie wszystkie wpisy są z roku " + CurrentRecordId.AsString() + ".\nChcesz zapisać?") != System.Windows.Forms.DialogResult.Yes)
                {
                    AddError("Nie wszystkie wpisy są z roku " + CurrentRecordId.AsString());
                    foreach (DataRow r in list)
                    {
                        r.SetColumnError("WRK_VATZ_DATA_WYSTAWIENIA", "Zły rok.");
                    }
                }
            }

            foreach (DataRow r in list)
                gvMain.ExpandRow(r);
        }

        private void gvMain_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (!LockEvents)
            {
                LockEvents = true;
                List<GridColumn> cols = new List<GridColumn>(){
                    colWRK_VATZ_DATA_WYSTAWIENIA,
                    colWRK_VATZ_DATA_NABYCIA_PRAW,
                    colWRK_VATZ_DATA_WPLYWU
                };

                if (e.Value.IsNotNull())
                {
                    if (cols.Contains(e.Column))
                    {
                        object current = e.Value;
                        if (current == null)
                            gvMain.SetRowCellValue(e.RowHandle, colMIESIAC, -1);
                        else
                        {
                            gvMain.SetRowCellValue(e.RowHandle, colMIESIAC, current.AsDateTime().Month);
                        }
                        foreach (GridColumn c in cols)
                        {
                            if (c != e.Value)
                            {
                                if (gvMain.GetRowCellValue(e.RowHandle, c).IsNull())
                                {
                                    gvMain.SetRowCellValue(e.RowHandle, c, e.Value);
                                }
                            }
                        }
                    }
                }
                LockEvents = false;
            }
        }
        
        protected override bool Save()
        {
            Manager.AutoCommit = false;
            bool result = base.Save();
            if (result && OptionCache.GetOptionBoolValue(OptionNames.AddVatZToKpir))
            {
                result = WrkTools.AddVatZToKpir(wrkVatZDataSet, Manager);
                if (!result)
                {
                    this.ShowDxErrorDialog("Błąd dodawania faktur do KPiR.");
                }
            }
            if (result)
                Manager.Commit();
            else
                Manager.Rollback();
            return result;
        }

        private void bbiDodajDoKPiR_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DataRow[] rows = wrkVatZDataSet.WRK_VATZ.Select("DODAJ_DO_KPIR = 1", null, DataViewRowState.CurrentRows);
            if (rows.Length > 0)
            {
                Manager.AutoCommit = true;
                bool res = WrkTools.AddVatZToKpir(wrkVatZDataSet, rows, Manager);
                if (res)
                {
                    this.ShowDxInfoDialog("Faktury dodane do KPiR.");
                    foreach (DataRow r in rows)
                        r["DODAJ_DO_KPIR"] = false;
                }
                else
                {
                    this.ShowDxErrorDialog("Błąd dodawania faktur do KPiR");
                }
            }
        }

        private void bbiZapiszJako_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gcMain.FocusedView != null)
            {
                gcMain.FocusedView.CloseEditor();
                gcMain.FocusedView.UpdateCurrentRow();
            }

            DataRow row = gvMain.GetFocusedDataRow();
            if (row != null)
            {
                ObjectDialogResult dlg = InputFormText.ShowInputDialog("Nazwa:");
                if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    string msg = "";
                    bool result = WrkTools.SaveVatZAsPredef(row, dlg.Value.AsString(), ref msg);
                    if (!result)
                    {
                        if (msg.IsNull())
                            msg = "Błąd zapisu.";
                        this.ShowDxErrorDialog(msg);
                    }
                    else
                    {
                        this.ShowDxInfoDialog("Faktura zapisana jako wzór.");
                    }
                }
            }
        }

        private void BrowserSettings_AdditionalBrowserValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            e.Cancel = true;
            DataRow r = gvMain.GetFocusedDataRow();
            WrkTools.AddVatZFromPredef(wrkVatZDataSet, e.NewValue.AsInt(), r);
        }

        private void bbiDrukuj_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RaportTools.FormMonthRaportPrint.ShowPrintDialog(CurrentRecordId.AsInt(), new raportVatZ());
        }
    }
}
